package com.klhappy.houyuan.utils;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by MrPu on 15/11/24.
 */
public class JsonCode {
    public static <T> T getClass(JsonElement jsonString, Class<T> cls) {
        T t = null;
        try {
            Gson gson = new Gson();
            t = gson.fromJson(jsonString, cls);
        } catch (Exception e) {
        }
        return t;
    }

    public static <T> List<T> getClassList(JsonElement jsonString, Class<T> cls) {
        List<T> list = new ArrayList<T>();
        try {
            Gson gson = new Gson();
            JsonArray array = jsonString.getAsJsonArray();
            for (int i = 0; null != array && i < array.size(); i++) {
                list.add(gson.fromJson(array.get(i), cls));
            }
        } catch (Exception e) {
        }
        return list;
    }

    public static List<Map<String, Object>> getMapList(JsonElement jsonString) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        try {
            Gson gson = new Gson();
            list = gson.fromJson(jsonString, new TypeToken<List<Map<String, Object>>>() {
            }.getType());
        } catch (Exception e) {
        }
        return list;
    }
}
